package com.hexiang.web;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hexiang.response.CommonResponse;
import com.hexiang.service.TaskService;
import com.hexiang.utils.WebAsyncTaskUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.async.WebAsyncTask;

import javax.annotation.Resource;
import java.util.Map;

@RestController
@Slf4j
public class WebAsyncTaskController {

    @Resource
    private ObjectMapper objectMapper;

    private final TaskService taskService;

    @Autowired
    public WebAsyncTaskController(TaskService taskService) {
        this.taskService = taskService;
    }

    @GetMapping(value = "/webAsyncTask", produces = "text/html")
    public WebAsyncTask<String> webAsyncTask() {
        log.info("webAsyncTaskStart");
        // 初始化时指定超时时间
        WebAsyncTask<String> result = WebAsyncTaskUtils.instance(1000,taskService::execute);
        log.info("webAsyncTaskEnd");
        return result;
    }

    @PostMapping(value = "/webAsyncTaskPost", produces = "application/json")
    public WebAsyncTask<CommonResponse> webAsyncTaskPost(@RequestBody String jsonString) throws JsonProcessingException {
        log.info("webAsyncTaskPostStart");
        String name = (String) objectMapper.readValue(jsonString, Map.class).get("name");
        // 初始化时指定超时时间
        WebAsyncTask<CommonResponse> result = WebAsyncTaskUtils.instance(1000,() -> taskService.execute(name));
        log.info("webAsyncTaskPostEnd");
        return result;
    }

    @GetMapping(value = "/webAsyncTaskTimeout", produces = "application/json")
    public WebAsyncTask<String> webAsyncTaskTimeout() {
        log.info("webAsyncTaskTimeoutStart");
        // 初始化时指定超时时间
        WebAsyncTask<String> result = WebAsyncTaskUtils.instance(1000,taskService::timeout);
        log.info("webAsyncTaskTimeoutEnd");
        return result;
    }

    @GetMapping(value = "/webAsyncTaskErr", produces = "application/json")
    public WebAsyncTask<CommonResponse> webAsyncTaskErr() {
        log.info("webAsyncTaskErrStart");
        // 初始化时指定超时时间
        WebAsyncTask result = WebAsyncTaskUtils.instance(1000,taskService::executeErr);
        log.info("webAsyncTaskErrEnd");
        return result;
    }
}